<template>
    <div class="contant">
        <div class="operatingArea">
            <div class="filter">
                <div class="filter-item">
                    <label for="">所属单位：</label>
                    <el-select
                        v-model="searchForm.depId"
                        class="m-2"
                        placeholder="请选择所属单位"
                        style="width: 155px"
                        :disabled="localTypeUnit != '1'"
                    >
                        <el-option
                            v-for="item in depIdList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </div>
                <div class="filter-item">
                    <label for="">权责名称：</label>
                    <el-input
                        v-model="searchForm.roleName"
                        placeholder="请输入权责名称"
                        style="width: 155px"
                        clearable
                    />
                </div>
                <div class="filter-item">
                    <el-button
                        size="default"
                        type="primary"
                        @click="search"
                    >查询</el-button>
                </div>
            </div>

            <div class="filter addBtn">
                <div class="filter-item">
                    <el-button
                        type="primary"
                        @click="handleClick('add')"
                    >新增</el-button>
                </div>
            </div>
        </div>
        <el-table
            :data="roleList"
            style="width: 100%"
            highlight-current-row
            :cell-style="{ 'text-align': 'center' }"
            :header-cell-style="headerCellStyle"
            :row-class-name="tableRowClassName"
            size="default"
        >
            <el-table-column
                type="index"
                label="序号"
                width="55"
            />
            <el-table-column
                prop="depId"
                label="所属单位"
            >
                <template #default="scope">
                    {{ depNameTranslate(scope.row.depId) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="roleName"
                label="权责名称"
            />
            <el-table-column
                prop="relateCount"
                label="关联用户数"
            />
            <el-table-column
                prop="roleComments"
                label="权责描述"
            />
            <el-table-column
                fixed="right"
                label="操作"
                width="190"
            >
                <template #default="scope">
                    <el-button
                        text
                        type="primary"
                        size="small"
                        @click="handleClick('detail', scope.row)"
                    >详情</el-button>
                    <el-button
                        text
                        type="primary"
                        size="small"
                        @click="handleClick('edit', scope.row)"
                    >编辑</el-button>
                    <el-button
                        text
                        type="danger"
                        size="small"
                        @click="handleClick('delete', scope.row)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="searchForm.pageNo"
            v-model:page-size="searchForm.pageSize"
            layout="total, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="paginationStyle"
        />
    </div>
    <el-dialog
        v-model="addRoleVisible"
        :title="addRoleVisibleName"
        width="700"
    >
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
            status-icon
            :inline="true"
        >
            <el-form-item
                label="所属单位："
                prop="depId"
                required
            >
                <el-select
                    v-model="ruleForm.depId"
                    class="m-2"
                    placeholder="请选择所属单位"
                    style="width: 190px"
                    :disabled="localTypeUnit != '1'"
                >
                    <el-option
                        v-for="item in depIdList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item
                label="权责名称："
                prop="roleName"
                required
            >
                <el-input
                    v-model="ruleForm.roleName"
                    style="width: 190px"
                    :disabled="addRoleVisibleType == 'detail'"
                />
            </el-form-item>
            <el-form-item
                label="权责编码："
                prop="roleCode"
                required
            >
                <el-input
                    v-model="ruleForm.roleCode"
                    style="width: 190px"
                    :disabled="addRoleVisibleType == 'detail'"
                />
            </el-form-item>
            <el-form-item
                label="权责描述："
                prop="roleComments"
                style="width: 596px"
                required
            >
                <el-input
                    v-model="ruleForm.roleComments"
                    :disabled="addRoleVisibleType == 'detail'"
                />
            </el-form-item>
        </el-form>
        <div class="setAuthority">设置权限</div>

        <!-- <el-tabs
            v-model="activeName"
            class="demo-tabs"
            style="padding: 0 20px; height: 360px"
        >
            <el-tab-pane
                label="权限设置"
                name="first"
            >
                <el-scrollbar style="height: 300px">
                    <el-tree
                        ref="treeRef"
                        style="max-width: 600px"
                        :data="dataSource"
                        show-checkbox
                        default-expand-all
                        node-key="id"
                        highlight-current
                        :props="defaultProps"
                    />
                </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane
                label="菜单设置"
                name="second"
            >正在开发中...</el-tab-pane>
        </el-tabs> -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addRoleVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    v-if="addRoleVisibleType !== 'detail'"
                    @click="submitForm(ruleFormRef)"
                >
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import menuHttp from "@/https/menu.js";
import userHttp from "@/https/user.js";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, reactive, ref } from "vue";
const addRoleVisible = ref(false);
const activeName = ref("first");
const roleList = ref();

const searchForm = reactive({
    depId: "",
    roleName: "",
    pageNo: 1,
    pageSize: 10,
});
const depIdList = ref([
    { label: "公司", value: "1" },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const localTypeUnit = ref(Storage.localGet("depId"));
searchForm.depId = localTypeUnit.value;
const depNameTranslate = (depId) => {
    let depName = "";
    depIdList.value.forEach((item) => {
        if (item.value == depId) {
            depName = item.label;
        }
    });
    return depName;
};
const search = async () => {
    const res = await userHttp.queryRoleList(searchForm);
    if (res.data.code === 200) {
        roleList.value = res.data.data.records;
        total.value = res.data.data.total;
    }
};
// const menuGrantTreeIds = ref([]);
// const menuGrantTree = async () => {
//     // let params = {
//     //     pageNo: 1,
//     //     pageSize: 1000,
//     // };
//     const userId = ref(Storage.localGet("loginId"));
//     menuGrantTreeIds.value = [];
//     const res = await menuHttp.menuGrantTree({ userId: userId.value });
//     if (res.data.code === 200) {
//         res.data.data.forEach((item) => {
//             menuGrantTreeIds.value.push(item.id);
//         });
//     }
// };
let total = ref(0);
const handleSizeChange = (val) => {
    searchForm.pageSize = val;
    search();
};
const handleCurrentChange = (val) => {
    searchForm.pageNo = val;
    search();
};
const ruleFormRef = ref();
const ruleForm = reactive({
    id: "",
    depId: "",
    roleName: "",
    roleCode: "",
    roleComments: "",
});
const rules = reactive({
    depId: [
        {
            required: true,
            message: "请输入所属单位",
            trigger: "blur",
        },
    ],
    roleName: [
        {
            required: true,
            message: "请输入权责名称",
            trigger: "blur",
        },
    ],
    roleCode: [
        {
            required: true,
            message: "请输入权责编码",
            trigger: "blur",
        },
    ],
    roleComments: [
        {
            required: true,
            message: "请输入权责编码",
            trigger: "blur",
        },
    ],
});
const addRoleVisibleName = ref("新增");
const addRoleVisibleType = ref("add");
const handleClick = (type, row) => {
    ruleForm.roleName = "";
    ruleForm.roleCode = "";
    ruleForm.roleComments = "";
    addRoleVisibleType.value = type;
    addRoleVisibleName.value =
        type == "add" ? "新增权责" : type == "detail" ? "权责详情" : "编辑权责";
    addRoleVisible.value = type !== "delete";
    if (type == "add") {
        ruleForm.depId = localTypeUnit.value + "";
    } else if (type == "detail" || type == "edit") {
        ruleForm.id = row.id;
        ruleForm.depId = row.depId + "";
        ruleForm.roleName = row.roleName;
        ruleForm.roleCode = row.roleCode;
        ruleForm.roleComments = row.roleComments;
        menuRoleKey(row.id);
    } else if (type == "delete") {
        ElMessageBox.confirm(`确认删除权责【${row.roleName}】吗？`, `删除`, {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            let params = {
                id: row.id,
                roleName: row.roleName,
                roleCode: row.roleCode,
                roleComments: row.roleComments,
            };
            userHttp.roleDelRole(params).then((res) => {
                if (res.data.code === 200) {
                    search();
                } else {
                    ElMessage({
                        message: res.data.msg,
                        type: "error",
                    });
                }
            });
        });
    }
};
const treeRef = ref();
const dataSource = ref([]);
const defaultProps = {
    children: "children",
    label: "name",
};

const depsList = async () => {
    let params = {
        pageNo: 1,
        pageSize: 1000,
    };
    const res = await menuHttp.menuMenuList(params);
    if (res.data.code === 200) {
        dataSource.value = res.data.data;
    }
};
const menuRoleKey = async (id) => {
    const res = await menuHttp.menuRoleKeyGrant(id);
    if (res.data.code === 200) {
        console.log(res.data.data);
        let list = []
        res.data.data.menuIds.forEach(item => {
            if (!res.data.data.halfMenuIds.includes(item)) {
                list.push(item)
            }
        })
        console.log(list, 'list')
        treeRef.value.setCheckedKeys(list);
    }
};
const submitForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            let checkedKeys = treeRef.value.getCheckedKeys(false, true);
            let halfCheckedKeys = treeRef.value.getHalfCheckedKeys()
            let allCheckedKeys = checkedKeys.concat(halfCheckedKeys)
            if (checkedKeys.length == 0) {
                ElMessage({
                    message: "请勾选功能权限",
                    type: "warning",
                });
                return;
            }
            if (addRoleVisibleType.value == "add") {
                userHttp.roleAddRole(ruleForm).then((res) => {
                    if (res.data.code == 200) {
                        addRoleVisible.value = false;
                        let roleIds = [];
                        roleIds.push(res.data.data.id);
                        let params = {
                            menuIds: allCheckedKeys,
                            halfMenuIds: halfCheckedKeys,
                            roleIds: roleIds,
                        };
                        menuHttp.menuGrant(params).then((res) => {
                            if (res.data.code == 200) {
                                addRoleVisible.value = false;
                                ElMessage({
                                    message: "编辑成功",
                                    type: "success",
                                });
                                search();
                            }
                        });
                        ElMessage({
                            message: "新增成功",
                            type: "success",
                        });
                        search();
                    } else {
                        ElMessage({
                            message: res.data.msg,
                            type: "error",
                        });
                    }
                });
            } else if (addRoleVisibleType.value == "edit") {
                userHttp.roleUpdateRole(ruleForm).then((res) => {
                    let roleIds = [];
                    roleIds.push(ruleForm.id);
                    if (res.data.code == 200) {
                        addRoleVisible.value = false;
                        let params = {
                            menuIds: allCheckedKeys,
                            halfMenuIds: halfCheckedKeys,
                            roleIds: roleIds,
                        };
                        menuHttp.menuGrant(params).then((res) => {
                            if (res.data.code == 200) {
                                addRoleVisible.value = false;
                                ElMessage({
                                    message: "编辑成功",
                                    type: "success",
                                });
                                search();
                            }
                        });
                    } else {
                        ElMessage({
                            message: res.data.msg,
                            type: "error",
                        });
                    }
                });
            }
        } else {
            ElMessage({
                message: "提交错误",
                type: "danger",
            });
        }
    });
};
const headerCellStyle = () => {
    let style = {
        background: '#f2f3f5',
        // color: '#fff',
        textAlign: 'center'
    }
    return style
}
const tableRowClassName = ({ row, rowIndex }) => {
    if ((rowIndex + 1) % 2 === 0) {
        // return 'warning-row'
    }
    return ''
}
onMounted(() => {
    search();
    depsList();
});
</script>
<style scoped lang="less">
.contant {
    background: #fff;
    border-radius: 10px;
    box-sizing: border-box;
    padding-bottom: 16px;
    :deep(.el-tabs__nav) {
        padding: 0 20px !important;
    }
    :deep(.el-tabs__item) {
        font-weight: 400 !important;
        font-size: 14px;
    }
    :deep(.el-tabs__nav-wrap:after) {
        height: 1px;
    }
    :deep(.el-tab-pane) {
        padding: 0;
    }
    .operatingArea {
        padding: 0 10px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }
    .addBtn {
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        margin-bottom: 10px;
    }
}
.filter {
    flex-wrap: wrap;
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 10px 15px;
    .filter-item {
        margin: 0 15px 15px 0px;
        display: flex;
        flex-direction: row;
        align-items: center;
        label {
            font-size: 14px;
            color: #333;
            display: inline-block;
            white-space: nowrap;
        }
    }
}
.setAuthority {
    padding-left: 10px;
    border-left: 4px solid #409eff;
    font-size: 16px;
    font-weight: 400;
    margin: 10px 0;
}

.paginationStyle {
    justify-content: flex-end;
    margin-top: 10px;
}
</style>